package org.example.day12;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 4.2.3 类ReentrantReadWriteLock 的使用: 读写互斥
 */
public class MyThread6 {
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void read() {
        try {
            //获取读锁
            lock.readLock().lock();
            System.out.println("获得读锁 " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
            System.out.println("释放读锁 " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
        }
    }

    public void write() {
        try {
            //获取写锁
            lock.writeLock().lock();
            System.out.println("获得写锁 " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
            System.out.println("释放写锁 " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread6 m6 = new MyThread6();
        Thread6A ta = new Thread6A(m6);
        ta.setName("A");
        ta.start();
        Thread.sleep(1000);
        Thread6B tb = new Thread6B(m6);
        tb.setName("B");
        tb.start();
    }
}

class Thread6A extends Thread {
    private MyThread6 m6;

    public Thread6A(MyThread6 m6) {
        this.m6 = m6;
    }

    @Override
    public void run() {
        m6.read();
    }
}

class Thread6B extends Thread {
    private MyThread6 m6;

    public Thread6B(MyThread6 m6) {
        this.m6 = m6;
    }

    @Override
    public void run() {
        m6.write();
    }
}